package com.xhsj.user.pms.workflow.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import com.xhsj.user.event.event.MessageEvent;
import com.xhsj.user.hr.system.entity.TbGlobalUser;
import com.xhsj.user.hr.system.mapper.TbGlobalRoleMapper;
import com.xhsj.user.hr.system.mapper.TbGlobalUserMapper;
import com.xhsj.user.hr.system.query.RoleNameInfo;
import com.xhsj.user.hr.system.query.UserNameInfo;
import com.xhsj.user.pms.common.constant.IdentifyConstant;
import com.xhsj.user.pms.common.constant.JumpConstant;
import com.xhsj.user.pms.patent.domain.*;
import com.xhsj.user.pms.patent.mapper.*;
import com.xhsj.user.pms.patent.query.InventorListQuery;
import com.xhsj.user.pms.patent.query.OperationerListQuery;
import com.xhsj.user.pms.patent.query.PatentApplyCostQuery;
import com.xhsj.user.pms.patent.query.PatentApplyFilePageQuery;
import com.xhsj.user.pms.patent.service.DisclosureService;
import com.xhsj.user.pms.patent.service.TbPamInventorProposalIprService;
import com.xhsj.user.pms.patent.service.impl.DisclosureServiceImpl;
import com.xhsj.user.pms.workflow.domain.WorkflowComplete;
import com.xhsj.user.pms.workflow.domain.WorkflowIdentitylink;
import com.xhsj.user.pms.workflow.domain.WorkflowLink;
import com.xhsj.user.pms.workflow.dto.ExecProgressDto;
import com.xhsj.user.pms.workflow.mapper.*;
import com.xhsj.user.pms.workflow.model.RuningTaskModel;
import com.xhsj.user.pms.workflow.model.RuningTaskProposalIprModel;
import com.xhsj.user.pms.workflow.model.WorkFlowScheduleModel;
import com.xhsj.user.pms.workflow.model.WorkflowIdentitylinkModel;
import com.xhsj.user.pms.workflow.service.WorkflowExecService;
import com.xhsj.user.pms.workflow.service.WorkflowIdentityLinkService;
import com.xhsj.user.sms.transfer.mapper.TbTaskTransferMapper;
import com.xhsj.user.utils.IdGen;
import com.xhsj.user.utils.Message;
import com.xhsj.user.utils.StringUtils;
import com.xhsj.user.utils.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.time.LocalDate;
import java.util.*;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * @Description:
 * @Auther: 罗季嘉
 * @Date: 2020/1/16 16:09
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class WorkflowExecServiceImpl implements WorkflowExecService {
    @Autowired
    private WorkflowExecMapper workflowExecMapper;
    @Autowired
    private WorkflowIdentityLinkService workflowIdentityLinkService;
    @Autowired
    private WorkflowIdentitylinkMapper workflowIdentityLinkMapper;
    @Autowired
    private WorkflowLinkMapper workflowLinkMapper;
    @Autowired
    private OpinionMapper opinionMapper;
    @Autowired
    private OpinionFileMapper opinionFileMapper;
    @Autowired
    private DisclosureMapper disclosureMapper;
    @Autowired
    private PatentFileMapper patentFileMapper;
    @Autowired
    private OpinionShipMapper opinionShipMapper;
    @Autowired
    private TbGlobalUserMapper userMapper;
    @Autowired
    private WorkflowCompleteMapper workflowCompleteMapper;

    @Autowired
    private PatentMapper patentMapper;
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private DisclosureInventorMapper disclosureInventorMapper;
    @Autowired
    private TbPamJudgesReviewRecordMapper tbPamJudgesReviewRecordMapper;

    @Autowired
    private PatentApplyProjectMapper patentApplyProjectMapper;
    @Autowired
    private PatentApplyFilePageMapper patentApplyFilePageMapper;
    @Autowired
    private PatentApplyCostMapper patentApplyCostMapper;
    @Autowired
    private TbPamJudgesReviewRecordFileMapper tbPamJudgesReviewRecordFileMapper;
    @Autowired
    private TbPamInventorProposalIprService tbPamInventorProposalIprService;

    @Autowired
    private TbPamInventorProposalIprMapper tbPamInventorProposalIprMapper;

    @Autowired
    private JudgesUserMapper judgesUserMapper;

    @Autowired
    private WorkflowExecService workflowExecService;
    @Autowired
    private WorkflowIdentitylinkMapper workflowIdentitylinkMapper;
    @Autowired
    private JudgesMapper judgesMapper;

    @Autowired
    private TbPamPatentOverseasFileMapper tbPamPatentOverseasFileMapper;

    //流程专员
    @Value("${rolekeyname.assistantName}")
    private String assistantName;

    /**
     * 根据专利ID查询流程进度信息集合
     *
     * @param disclosureId
     * @return
     */
    @Override
    public IPage<WorkFlowScheduleModel> getWorkFlowSchedule(String disclosureId, int pageNum, int pageSize) {
        IPage<WorkFlowScheduleModel> page = new Page<>(pageNum, pageSize);
        IPage<WorkFlowScheduleModel> workFlowScheduleList = workflowExecMapper.getWorkFlowSchedule(page, disclosureId);
        List<WorkFlowScheduleModel> records = workFlowScheduleList.getRecords();
        for (WorkFlowScheduleModel workFlowSchedule : records) {
            StringBuilder sb = new StringBuilder();
            if (workFlowSchedule.getExamineStatus() == 0 && IdentifyConstant.USER.equals(workFlowSchedule.getLabel())) {
                // 得到处理人
                UserNameInfo userNameInfo = userMapper.getUserNameInfoByUserId(Long.valueOf(workFlowSchedule.getFullName()));
                String status = "";
                if(userNameInfo.getStatus() == 1)
                    status = "(已离职)";
//                String fullNameByUserId = userMapper.getFullNameByUserId(workFlowSchedule.getFullName());
                workFlowSchedule.setFullName(userNameInfo.getFullName()+status);
            }
            if (workFlowSchedule.getExamineStatus() == 0 && IdentifyConstant.ROLE.equals(workFlowSchedule.getLabel())) {
                // 得到处理人
                List<TbGlobalUser> userListByRoleId = userMapper.getUserListByRoleId(workFlowSchedule.getFullName());
                if (userListByRoleId != null) {
                    for (TbGlobalUser user : userListByRoleId) {
                        if (user.getStatus() == 0) {
                            sb.append(String.valueOf(user.getFullName() + " "));
                        }

                    }
                }
                workFlowSchedule.setFullName(sb.toString());
            }

            if(StringUtils.isBlank(workFlowSchedule.getFullName()) && workFlowSchedule.getExamineStatus() == 0
                    && IdentifyConstant.ROLE.equals(workFlowSchedule.getLabel())) {
                workFlowSchedule.setFullName("无在职用户");
            }

            if (workFlowSchedule.getNodeNum()==0){
                workFlowSchedule.setNodeNum(records.size()+1);
            }
        }
        return workFlowScheduleList;
    }


    //  主管审核保存
    @Override
    public void managerWorkFlowProgress(ExecProgressDto param) throws Exception {

        // 审核流程
        execProgress2(param);
    }


    // 保存评审会审核意见记录
    @Override
    public Message saveJudgesReviewRecord(Map<String, Object> param) {
        try {
            String opinionText = String.valueOf(param.get("reviewOpinionText"));
            List<Map<String, Object>> opinionFileList = (List<Map<String, Object>>) param.get("reviewRecordFile");
            if (!StringUtils.isBlank(opinionText) || opinionFileList.size() != 0) {
                Date updateDate = new Date();
                TbPamJudgesReviewRecord opinion = new TbPamJudgesReviewRecord();
                opinion.setType(StringUtils.toInteger(param.get("type")));
                opinion.setOpinionText(opinionText);
                //        是修改审批意见还是新增
                opinion.setUpdateDate(updateDate);//修改时间
                opinion.setUpdateBy(String.valueOf(param.get("userId")));
                opinion.setDisclosureId(String.valueOf(param.get("disclosureId")));
                opinion.setJudgesUserId(String.valueOf(param.get("userId")));
                //            新增
                String uuid = IdGen.generateUUID();
                opinion.setId(uuid);
                opinion.setBeJudgesUserId(String.valueOf(param.get("ownerAs")));
                opinion.setCreateBy(String.valueOf(param.get("userId")));
                opinion.setCreateDate(updateDate);//时间
                int i = tbPamJudgesReviewRecordMapper.insert(opinion);
                log.info("保存评审会审核意见记录相关信息，{}", i);
                if (i == 1) {
                    param.put("reviewRecordId", uuid);
                    param.put("currentDate", updateDate);
                    if (opinionFileList.size() != 0) {
                        //保存审批文件
                        Message message = saveTbPamJudgesReviewRecordFile(param);
                        if (!("0".equals(String.valueOf(message.get("code"))))) {
                            return Message.error(1, "工单流转异常请联系管理员");
                        }
                    }
                }
                return Message.success("当前工单流转成功");
            }
            return Message.success("当前工单流转成功");
        } catch (Exception e) {
            log.error("修改审批相关信息错误，{}", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//关键
            return Message.error(1, "工单流转异常请联系管理员");
        }
    }

    //获取当前交底书所在的流程
    @Override
    public Long getWorkFlowExec(String disclosureId) {
        return workflowExecMapper.getWorkFlowExec(disclosureId);
    }


    //专利代办数
    @Override
    public Integer patentAgencyNum(int userId) {
        List<String> roleList = userMapper.getRoleListByUserIdList(
                Arrays.asList(String.valueOf(String.valueOf(userId)).split(",")));
        return workflowExecMapper.patentAgencyNum(userId, roleList);
    }


    //审批意见文件相关
    public Message saveTbPamJudgesReviewRecordFile(Map<String, Object> param) {
        try {
            //保存文件
            String reviewRecordId = String.valueOf(param.get("reviewRecordId"));
            Date date = (Date) param.get("currentDate");
            String userId = String.valueOf(param.get("userId"));
            List<Map<String, Object>> opinionFileList = (List<Map<String, Object>>) param.get("reviewRecordFile");
            for (Map<String, Object> opinionFile : opinionFileList
            ) {
                TbPamJudgesReviewRecordFile opinionFileEntity = StringUtils.toJavaBean(opinionFile, TbPamJudgesReviewRecordFile.class);
                opinionFileEntity.setId(IdGen.generateUUID());
                opinionFileEntity.setType(0);
                opinionFileEntity.setCreateDate(date);
                opinionFileEntity.setUpdateDate(date);
                opinionFileEntity.setCreateBy(userId);
                opinionFileEntity.setUpdateBy(userId);
                opinionFileEntity.setReviewRecordId(reviewRecordId);
                int i = tbPamJudgesReviewRecordFileMapper.insert(opinionFileEntity);
                if (i != 1) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//关键
                    return Message.error(1, "工单流转异常请联系管理员");
                }
            }
            return Message.success("当前工单流转成功");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//关键
            log.info("修改审批文件相关信息错误，{}", e.getMessage());
            return Message.error(1, "工单流转异常请联系管理员");
        }
    }

    /**
     * 递交申请文件
     * @author 苏小林
     * @date 2021/1/13 14:11
     * @param: param
     * @return: com.xhsj.user.utils.Message
     */
    @Override
    public void submitApplicationFile(ExecProgressDto param) throws Exception {
        Disclosure disclosure = disclosureMapper.getDisclosureByDisclosureId(param.getDisclosureId());
        if (disclosure == null) {
            throw new Exception("交底书不存在或已经删除");
        }
        Patent patent = new Patent();
        patent.setCreatedDate(disclosure.getCreatedTime());
        patent.setProposerId(disclosure.getCreatedUser());
        patent.setName(disclosure.getName());
        patent.setNum(disclosure.getNum());
        patent.setInventor(disclosure.getInventor());
        patent.setApplicationTime(new Date());
        patent.setId(IdGen.generateUUID());
        patent.setUpdateBy(param.getUserId());
        patent.setCreatedBy(param.getUserId());
        patent.setDelFlag(2);
        patent.setUpdateTime(new Date());
        int save = patentMapper.insert(patent);
        if (save == 0) {
            throw new Exception("保存专利相关文件错误");
        }
        param.setSendAliyun(false);
        this.execProgress2(param);
    }

    //    通知提交页
    @Override
    public void noticeCommitWorkFlowProgress(Map<String, Object> param) throws Exception {

        if (!"5".equals(String.valueOf(param.get("flowCode")))) {
        ExecProgressDto execProgressDto = new ExecProgressDto();
        execProgressDto.setDisclosureId(StringUtils.getStringValue(param,"disclosureId"));
        execProgressDto.setFlowCode(StringUtils.getIntegerValue(param,"flowCode"));
        execProgressDto.setNodeId(StringUtils.getStringValue(param,"nodeId"));
        execProgressDto.setNodeName(StringUtils.getStringValue(param,"nodeName"));
        execProgressDto.setFullName(StringUtils.getStringValue(param,"fullName"));
        execProgressDto.setProcessTaskId(StringUtils.getStringValue(param,"processTaskId"));
        execProgressDto.setJumpForm(StringUtils.getIntegerValue(param,"jumpForm"));
        execProgressDto.setLabel(IdentifyConstant.ROLE);
        List<Long> users = (List<Long>) param.get("users");
        execProgressDto.setUsers(users);

//        String startCreateTime = StringUtils.getStringValue(param, "startCreateTime");
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        execProgressDto.setCreateTime(simpleDateFormat.parse(startCreateTime));

        // 流程执行
        execProgressDto.setSendAliyun(false);
        this.execProgress2(execProgressDto);
        }

        Long userId = UserUtils.getLoginAppUser().getUserId();
        PatentApplyProject patentApplyProject = StringUtils.toJavaBean(param, PatentApplyProject.class);
        patentApplyProject.setCreatedBy(userId);
        patentApplyProject.setCreatedDate(new Date());
        patentApplyProject.setDelFlag(0);
        int insert =0;
        if (StringUtils.isNotBlank(patentApplyProject.getId())) {
            insert =  patentApplyProjectMapper.updateById(patentApplyProject);
        }else{
            patentApplyProject.setId(IdGen.generateUUID());
            insert = patentApplyProjectMapper.insert(patentApplyProject);
        }
        if (insert != 1) {
            log.error("保存专利申请项目主表出错");
            throw new Exception("保存专利申请项目主表出错");
        }

        // 删除根据apply_project_id
        patentApplyCostMapper.deleteByApplyProjectId(patentApplyProject.getId());
        List<PatentApplyCostQuery> patentApplyCostList = patentApplyProject.getPatentApplyCostList();
        if (!patentApplyCostList.isEmpty()) {
            for (PatentApplyCostQuery patentApplyCost : patentApplyCostList) {
                patentApplyCost.setApplyProjectId(patentApplyProject.getId());
                patentApplyCost.setId(IdGen.generateUUID());
                patentApplyCost.setCreatedBy(userId);
                patentApplyCost.setCreatedDate(new Date());
                patentApplyCost.setDelFlag(0);
                PatentApplyCost patentApplyCost1 = new PatentApplyCost();
                BeanUtils.copyProperties(patentApplyCost,patentApplyCost1);
                if (StringUtils.isBlank(patentApplyCost.getAmount()))
                    patentApplyCost1.setAmount(null);
                 else
                patentApplyCost1.setAmount(String.valueOf(patentApplyCost.getAmount()));
                int insert1 = patentApplyCostMapper.insert(patentApplyCost1);
                if (insert1 != 1) {
                    log.error("保存专利申请项目费用出错");
                    throw new Exception("保存专利申请项目费用出错");
                }
            }
        }

       // 删除文件根据apply_project_id
        patentApplyFilePageMapper.deleteByProjectId(patentApplyProject.getId());
        List<PatentApplyFilePageQuery> patentApplyFilePageList = patentApplyProject.getPatentApplyFilePageList();
        if (!patentApplyFilePageList.isEmpty()) {
            for (PatentApplyFilePageQuery patentApplyFilePage : patentApplyFilePageList) {
                patentApplyFilePage.setId(IdGen.generateUUID());
                patentApplyFilePage.setApplyProjectId(patentApplyProject.getId());
                patentApplyFilePage.setCreatedBy(userId);
                patentApplyFilePage.setCreatedDate(new Date());
                patentApplyFilePage.setDelFlag(0);
                PatentApplyFilePage  patentApplyFilePage1 = new PatentApplyFilePage();
                BeanUtils.copyProperties(patentApplyFilePage,patentApplyFilePage1);
                if (StringUtils.isBlank(patentApplyFilePage.getPageNum()))
                    patentApplyFilePage1.setPageNum("");
                else
                    patentApplyFilePage1.setPageNum(String.valueOf(patentApplyFilePage.getPageNum()));
                int insert1 = patentApplyFilePageMapper.insert(patentApplyFilePage1);
                if (insert1 != 1) {
                    log.error("保存专利申请项目文件出错");
                    throw new Exception("保存专利申请项目文件出错");
                }
            }
        }

        // 删除文件根据apply_project_id
        List<Integer> fileTypeList = Arrays.asList(5);
        patentFileMapper.deleteByDiscId(patentApplyProject.getId(),fileTypeList);
        tbPamPatentOverseasFileMapper.deleteByDataId(patentApplyProject.getDisclosureId());
        List<PatentFile> patentFileList = patentApplyProject.getPatentApplyFileList();
        if (!patentFileList.isEmpty()) {
            for (PatentFile patentFile : patentFileList) {
                if ("1".equals(String.valueOf(patentFile.getUploadType()))) {
                patentFile.setPatentFileId(IdGen.generateUUID());
                patentFile.setDiscId(patentApplyProject.getId());
                patentFile.setOwnerAs(String.valueOf(userId));
                int insert1 = patentFileMapper.insert(patentFile);
                if (insert1 != 1) {
                    log.error("保存专利申请项目文件出错");
                    throw new Exception("保存专利申请项目文件出错");
                }
                }else if("2".equals(String.valueOf(patentFile.getUploadType()))){
                    TbPamPatentOverseasFile tbPamPatentOverseasFile = new TbPamPatentOverseasFile();
                    BeanUtils.copyProperties(patentFile,tbPamPatentOverseasFile);
                    tbPamPatentOverseasFile.setDataId(patentApplyProject.getDisclosureId());
                    tbPamPatentOverseasFile.setCreateBy(userId);
                    tbPamPatentOverseasFile.setUpdateBy(userId);
                    tbPamPatentOverseasFile.setCreateDate(patentFile.getUploadTime());
                    tbPamPatentOverseasFile.setUpdateDate(patentFile.getUploadTime());
                    tbPamPatentOverseasFile.setCreateName(patentFile.getOwnerUserFullName());
                    int insert1 = tbPamPatentOverseasFileMapper.insert(tbPamPatentOverseasFile);
                    if (insert1 != 1) {
                        log.error("保存专利答复文件出错");
                        throw new Exception("保存专利答复文件出错");
                    }
                }
            }

        }
    }

    /**
     * 专利审核列表
     *
     * @author 苏小林
     * @date 2020/2/24 15:13
     * @param: param
     * @return: java.util.List<java.util.Map>
     */
    @Override
    public IPage<ExamineModel> findPatentAuditList(Map<String, Object> param) {
        int pageNum = 1;
        int pageSize = 20;
        if (StringUtils.isNotNull(param.get("pageNum"))) {
            pageNum = Integer.parseInt(String.valueOf(param.get("pageNum")));
        }
        if (StringUtils.isNotNull(param.get("pageSize"))) {
            pageSize = Integer.parseInt(String.valueOf(param.get("pageSize")));
        }
        // 专利名称
        String name = Objects.isNull(param.get("name")) ? "" : String.valueOf(param.get("name"));
        //案卷号
        String archivesNum = Objects.isNull(param.get("archivesNum")) ? "" : String.valueOf(param.get("archivesNum"));
//
        String userId = String.valueOf(UserUtils.getLoginAppUser().getUserId());
        List<String> roleList = userMapper.getRoleListByUserIdList(
                Arrays.asList(String.valueOf(userId).split(",")));
        String type = String.valueOf(param.get("type"));
        IPage<ExamineModel> iPage = new Page<>();
        IPage<ExamineModel> page = new Page<>(pageNum, pageSize);

//        申请费已交 和 其他节点的案件拆分
        switch (type) {
            // 待审核
            case "2":
            case "5":
            case "6":
                // 流程专员得用户id
                    List<Long> userIdList = userMapper.getUserIdByRoleName(assistantName);
                    if (userIdList.contains(new Long(userId)) && "6".equals(type) ) {
                        iPage = workflowExecMapper.findPatentAuditListAssistantName(page, 0,
                                name, archivesNum, param);
                    }else {
                iPage = workflowExecMapper.findPatentAuditListInComplete(page, 0, userId,
                        name, roleList, archivesNum,param);
                for (ExamineModel examineModel : iPage.getRecords()) {
                    if (StringUtils.isNotBlank(examineModel.getJudgesId())) {
                        if (examineModel.getJumpForm() == JumpConstant.JUDGES_FIRST_TRIAL_AUDIT || examineModel.getJumpForm() == JumpConstant.JUDGES_FINAL_TRIAL_AUDIT) {
                            List<String> judgesIdList = Arrays.asList(examineModel.getJudgesId().split(","));
                            if (StringUtils.isBlank(examineModel.getPatentUserId())) {
                                if (judgesIdList.contains(userId))
                                    examineModel.setIsShowButton(0);
                            } else if (judgesIdList.contains(userId) || examineModel.getPatentUserId().equals(userId)) {
                                examineModel.setIsShowButton(0);
                            } else {
                                examineModel.setIsShowButton(1);
                            }
                        }
                    }
                }
                }
                break;
            // 审核通过
            case "3":
                iPage = workflowExecMapper.findPatentAuditListComplete(page, 1, UserUtils.getLoginAppUser().getFullName(),
                        name, roleList, archivesNum,param);
                break;
            // 审核退回
            case "4":
                iPage = workflowExecMapper.findPatentAuditListComplete(page, 2, UserUtils.getLoginAppUser().getFullName(),
                        name, roleList, archivesNum,param);
                break;
        }
        List<ExamineModel> records = iPage.getRecords();
        // 技术领域
        List<String> collect = records.stream().map(ExamineModel::getDisclosureId).collect(Collectors.toList());
        if(collect != null && collect.size() != 0) {
//            collect = Arrays.asList("C5385C5F7F4046FEBE876B5035B99A70");
            Map<String,Map<String,String>> judgesById = judgesMapper.getJudgesById(collect);
            records.forEach(record -> {
                if (judgesById.containsKey(record.getDisclosureId())) {
                    record.setJudgesName(judgesById.get(record.getDisclosureId()).get("judgesName"));
                }
            });
            System.out.println(judgesById);
        }

        this.getOperationer(records);
        return iPage;
    }

    public void getOperationer(List<? extends ExamineModel> records){
        // 获取对应交底书id数组
        List<String> disclosureIdList = records.stream().map(item -> item.getDisclosureId()).collect(Collectors.toList());
        if(StringUtils.isNotBlank(disclosureIdList) && disclosureIdList.size() !=0 ) {
            // 发明人
            Map<String, InventorListQuery> inventorList = disclosureInventorMapper.getInventorList(disclosureIdList);
            // 获取操作人通过底书id
            Map<String, OperationerListQuery> adviceIprList = tbPamInventorProposalIprMapper.getAdviceIprList(disclosureIdList);
            records.forEach(item -> {
                if (adviceIprList.containsKey(item.getDisclosureId()) && !"003BFA10D8934DF992E34DED81787CCC".equals(item.getNodeId()) && !"19181F68A04841F2AE079A8D52925200".equals(item.getNodeId()))
                    item.setConveyancer(adviceIprList.get(item.getDisclosureId()).getFullName());
                if (inventorList.containsKey(item.getDisclosureId())){
                    item.setInventor(inventorList.get(item.getDisclosureId()).getInventor());
                }

            });

//            // 获取操作人通过底书id
//            Map<String, OperationerListQuery> operationerList = patentFileMapper.getOperationerList(disclosureIdList);
//            records.forEach(item -> {
//                if (operationerList.containsKey("3-" + item.getDisclosureId()))
//                    item.setConveyancer(operationerList.get("3-" + item.getDisclosureId()).getFullName());
//                else if (operationerList.containsKey("1-" + item.getDisclosureId()))
//                    item.setConveyancer(operationerList.get("1-" + item.getDisclosureId()).getFullName());
//            });
        }
    }

    @Override
    public boolean updateDisclosure(Map<String, Object> param) throws Exception {
        // 修改交底书名称
        Disclosure disclosure = StringUtils.toJavaBean(param, Disclosure.class);
        List<DisclosureInventor> inventorList = disclosure.getInventorList();
        if (inventorList != null && inventorList.size() > 0) {
            QueryWrapper<DisclosureInventor> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("disclosure_id", disclosure.getDisclosureId());
            disclosureInventorMapper.delete(queryWrapper);

            StringBuilder stringBuilder = new StringBuilder();
            for (DisclosureInventor disclosureInventor : inventorList) {
                String id = disclosureInventor.getId();
                disclosureInventor.setUpdateDate(new Date());
                stringBuilder.append(";" + disclosureInventor.getInventor() + ":" + disclosureInventor.getWeight() + "%");
                if (StringUtils.isBlank(id)) {
                    disclosureInventor.setId(IdGen.generateUUID());
                    disclosureInventor.setDisclosureId(disclosure.getDisclosureId());
                    disclosureInventor.setCreateBy(String.valueOf(param.get("createdUser")));
                    disclosureInventor.setCreateDate(new Date());
                }
                int insert = disclosureInventorMapper.insert(disclosureInventor);
                if (insert != 1) {
                    throw new Exception("修改交底书信息出错");
                }
            }
            String substring = stringBuilder.toString().substring(1);
            disclosure.setInventor(substring);
        }
        List<Long> inventorProposalIprs = disclosure.getInventorProposalIprs();
        if (inventorProposalIprs.size() > 1) {
            throw new Exception("只能选择一个IPR");
        }
        // 若是修改技术领域则需要修改节点为评审会初审和评审会终审以及初审确认和终审确认的审核人
        // 判断是否修改了技术领域
        List<RuningTaskModel> runingTask = disclosureMapper.getRuningTaskById(disclosure.getDisclosureId(),disclosure.getJudgesId());
        if (runingTask.size()>0) {
            // 获取最新的评审会成员
          List<Map<Long,Long>> judgesUserId = judgesUserMapper.getJudgesUserById(disclosure.getJudgesId());
            if (judgesUserId.size()==0) {
                throw new Exception("无评审会成员");
            }
            List<List<Long>> users=new ArrayList<>();
            for (Map<Long, Long> longLongMap : judgesUserId) {
                List<Long> list=new ArrayList<>();
                list.add(longLongMap.get("deptId"));
                list.add(longLongMap.get("userId"));
                users.add(list);
            }
            // 获取技术负责人
            Judges judges = judgesMapper.selectById(disclosure.getJudgesId());
            this.updateIdentityAndHi(judges.getPatentUserId(),users,runingTask,inventorProposalIprs);
        }
        int i = disclosureMapper.updateById(disclosure);
        if (i != 1) {
            throw new Exception("修改交底书信息出错");
        }

        // 若是修改建议ipr则需要修改节点为ipr查新评审会初审和评审会终审以及初审确认和终审确认的审核人，编写权力文件和说明书
        String nodeId = disclosure.getNodeId();
        updateAduiterByProposalIPR(nodeId,inventorProposalIprs,disclosure.getDisclosureId());

        //修改指派的ipr
        //根据交底书id删除指派ipr信息
        int i1 = tbPamInventorProposalIprService.deleteByDisclosure(disclosure.getDisclosureId());
        if (inventorProposalIprs != null) {
            if (inventorProposalIprs.size() > 0) {
                for (Long inventorProposalIpr : inventorProposalIprs) {
                    TbPamInventorProposalIpr tbPamInventorProposalIpr = new TbPamInventorProposalIpr();
                    tbPamInventorProposalIpr.setUserId(String.valueOf(inventorProposalIpr));
                    tbPamInventorProposalIpr.setDisclosureId(disclosure.getDisclosureId());
                    tbPamInventorProposalIpr.setCreateBy(String.valueOf(disclosure.getCreatedUser()));
                    tbPamInventorProposalIpr.setUpdateBy(String.valueOf(disclosure.getCreatedUser()));
                    if (!tbPamInventorProposalIprService.save(tbPamInventorProposalIpr)) {
                        throw new Exception("修改指派的ipr信息出错");
                    }
                }
            }
        }
        return true;
    }

    public void updateAduiterByProposalIPR(String nodeId,List<Long> inventorProposalIprs, String disclosureId) throws Exception {
        if ( "97BF5B1F73414EA9BBDB55C62D46B981".equals(nodeId)
                || "7524DFC3666B40C5A6E6EEFD063F06EA".equals(nodeId) ||
                "67409ADFDC384E46AA3F6B410113E495".equals(nodeId) ||
                "3AE5CBF5E43E444D8256929EC6BFF2C8".equals(nodeId) ||
                "39DB703EDD0A4A20AF858FBBED6BF6ED".equals(nodeId)){
            if (inventorProposalIprs.size()==0) {
                throw new Exception("当前节点建议ipr不能为空");
            }
            // 获取旧建议ipr
            List<Long> proposalIprs=tbPamInventorProposalIprMapper.getAdviceIpr(disclosureId);
            // 新建议ipr
            Long newProposalIpr = inventorProposalIprs.get(0);
            List<Long> judgesUserId = judgesUserMapper.getJudgesUserId(disclosureId);
            // 获取正在执行流程信息
            QueryWrapper<WorkflowIdentitylink> queryWrapper=new QueryWrapper();
            queryWrapper.eq("disclosure_id",disclosureId);
            queryWrapper.eq("node_id",nodeId);
            List<WorkflowIdentitylink> list = workflowIdentityLinkMapper.selectList(queryWrapper);
            for (WorkflowIdentitylink workflowIdentitylink : list) {
                if (!proposalIprs.contains(newProposalIpr) || proposalIprs.size() > 1) {
                    String nodeId1 = workflowIdentitylink.getNodeId();
                    if (("67409ADFDC384E46AA3F6B410113E495".equals(nodeId1) ||
                            "3AE5CBF5E43E444D8256929EC6BFF2C8".equals(nodeId1) ||
                            "39DB703EDD0A4A20AF858FBBED6BF6ED".equals(nodeId1))) {
                        // 删除待审核
                        workflowIdentityLinkMapper.deleteByDisclosureId(disclosureId);
                        workflowCompleteMapper.deleteHiForDisclosureAndNodeId(disclosureId,nodeId);
                        // 删除待历史审核
                        // 添加审核人为修改后的ipr
                        updateAduiter(workflowIdentitylink,newProposalIpr);
                        break;
                    }
                    // 判断当节点在初审终审时旧建议ipr是否是评审会成员
                    if ("97BF5B1F73414EA9BBDB55C62D46B981".equals(workflowIdentitylink.getNodeId())
                            || "7524DFC3666B40C5A6E6EEFD063F06EA".equals(workflowIdentitylink.getNodeId())) {
                        proposalIprs.add(newProposalIpr);
                        List<Long> subtract = (List<Long>) CollectionUtils.subtract(proposalIprs, judgesUserId);
                        if (subtract.size()>0 ) {
                            workflowIdentityLinkMapper.deleteByDisclosureIdAndUserId(disclosureId, subtract);
                            workflowCompleteMapper.deleteHiByDisclosureIdAndUserId(disclosureId, subtract);
                            // 添加审核人为修改后的ipr
                            if (!judgesUserId.contains(newProposalIpr)) {
                                updateAduiter(workflowIdentitylink,newProposalIpr);
                            }

                            break;
                        }
                    }
                }
            }

        }
    }

    // 添加审核人为修改后的ipr
    public void updateAduiter(WorkflowIdentitylink workflowIdentitylink,Long newProposalIpr) throws Exception {
        RuningTaskModel runingTaskModel = new RuningTaskModel();
        BeanUtils.copyProperties(workflowIdentitylink, runingTaskModel);
        this.insertIdentityAndHi(runingTaskModel, newProposalIpr);
    }

    public void saveAndUpdateOpinion2(ExecProgressDto param, String hiFlowExceId) throws Exception {
        String opinionText = param.getOpinionText();
        List<OpinionFile> opinionFileList = param.getOpinionFile();
        if (StringUtils.isNotBlank(opinionText)) {
            List<Long> users = param.getUsers();
            Date updateData = new Date();
            if (users != null) {
                for (Long user : users) {
                    Opinion opinion = new Opinion();
                    opinion.setOpinionText(opinionText);
                    //        是修改审批意见还是新增
                    opinion.setCompleteExecId(hiFlowExceId);
                    opinion.setUpdateTime(updateData);//修改时间
                    opinion.setDisclosureId(param.getDisclosureId());
                    opinion.setNodeId(param.getNodeId());
                    opinion.setOwnerAs(param.getUserId());
                    opinion.setReceivedBy(user);
                    if (StringUtils.isNull(opinion.getOpinionId())) {
                        String uuid = IdGen.generateUUID();
                        opinion.setOpinionId(uuid);
                        int i = opinionMapper.insert(opinion);
                        if (i == 1) {
                            if (opinionFileList.size() != 0) {
                                //保存审批文件
                                saveAndUpdateOpinionFile2(uuid, opinionFileList);
                            }
                        } else {
                            throw new Exception("保存审批意见异常");
                        }
                    }
                }
            }
        }
    }

    //审批意见文件相关
    public void saveAndUpdateOpinionFile2(String opinionId, List<OpinionFile> opinionFileList) throws Exception {
        //保存文件
        for (OpinionFile opinionFile : opinionFileList) {
            String uuid = IdGen.generateUUID();
            opinionFile.setOpinionFileId(uuid);
            int i = opinionFileMapper.insert(opinionFile);
            if (i == 1) {
                OpinionShip opinionShip = new OpinionShip();
                opinionShip.setOpinionShipId(IdGen.generateUUID());
                opinionShip.setFId(uuid);
                opinionShip.setOId(opinionId);
                int i1 = opinionShipMapper.insert(opinionShip);
                if (i1 != 1) {
                    throw new Exception("审批意见文件中间表相关异常");
                }
            } else {
                throw new Exception("审批意见文件相关异常");
            }
        }

    }

    /**
     * 执行流程
     */
    @Override
    public void execProgress3(ExecProgressDto param) throws Exception {
        // 删除当前用户的流程根据id
        int i = workflowIdentityLinkMapper.deleteByProcessTaskId(param.getProcessTaskId());
        if (i == 0) {
            log.error("删除正在执行中任务失败");
            throw new Exception("删除正在执行中任务失败");
        }

        // 修改历史任务状态
        WorkflowComplete workflowComplete = new WorkflowComplete();
        workflowComplete.setId(param.getProcessTaskId());
        workflowComplete.setUpdateTime(new Date());
        workflowComplete.setDealUser(param.getFullName());
        workflowComplete.setLabel(IdentifyConstant.USER);
        workflowComplete.setExamineStatus(1);// 审核通过
        int i1 = workflowCompleteMapper.updateById(workflowComplete);
        if (i1 == 0) {
            log.error("修改历史任务状态失败");
            throw new Exception("修改历史任务状态失败");
        }
        // 处理历史
//        WorkflowComplete workflowComplete = setWorkflowComplete(param);
//        String completeExecId = dealHiFlowExce(workflowComplete, 0, false);
        // 处理意见
        saveAndUpdateOpinion2(param, param.getProcessTaskId());
    }

    /**
     * 执行流程
     */
    @Override
    public void execProgress2(ExecProgressDto param) throws Exception {
        // 删除当前用户的流程
        int i = workflowIdentityLinkMapper.deleteByDisclosureId(param.getDisclosureId());
        if (i == 0 && !param.getStartFlow()) {
            throw new Exception("无流程");
        }

        if ("003BFA10D8934DF992E34DED81787CCC".equals(param.getNodeId())) { // 创建交底书
            // 处理历史
            WorkflowComplete workflowComplete = setWorkflowComplete(param);
            workflowComplete.setUpdateTime(new Date());
            createHiFlowExce(workflowComplete);
        } else {
            // 修改历史任务状态
            WorkflowComplete workflowComplete = new WorkflowComplete();
            workflowComplete.setId(param.getProcessTaskId());
            workflowComplete.setUpdateTime(new Date());
            workflowComplete.setDealUser(param.getFullName());
            workflowComplete.setLabel(IdentifyConstant.USER);
            if (param.getFlowCode() == 1 || param.getFlowCode() == 3) {
                workflowComplete.setExamineStatus(2);
            } else {
                workflowComplete.setExamineStatus(1);
            }
            int i1 = workflowCompleteMapper.updateById(workflowComplete);
            if (i1 == 0) {
                log.error("修改历史任务状态失败");
                throw new Exception("修改历史任务状态失败");
            }
        }

        // 下一个节点
        List<WorkflowLink> collect = workflowLinkMapper.selectLinkListByNodeId(param.getNodeId(), param.getFlowCode());
        if (collect.size() == 0) {
            throw new Exception("无下一个节点");
        }
        Disclosure disclosure = new Disclosure();
        // 设置下一个节点流程指定人
        for (WorkflowLink item : collect) {
            workflowIdentityLinkService.setProgressIdentify2(param,
                    item.getNextNode(), item.getNodeName());
            disclosure.setNodeId(item.getNextNode());
            disclosure.setNodeName(item.getNodeName());
            if ("闭案".equals(item.getNodeName()) || "结案".equals(item.getNodeName())) {
                WorkflowComplete workflowComplete = setWorkflowComplete(param);
                workflowComplete.setNodeId(item.getNextNode());
                workflowComplete.setCreateTime(new Date(System.currentTimeMillis()+1000));
                workflowComplete.setNodeName(item.getNodeName());
                workflowComplete.setUpdateTime(new Date(System.currentTimeMillis()+1000));
                createHiFlowExce(workflowComplete);
            }
        }
        // 处理意见
        saveAndUpdateOpinion2(param, param.getProcessTaskId());
        // 修改申请表节点id和节点名
        disclosure.setDisclosureId(param.getDisclosureId());
        int i2 = disclosureMapper.updateById(disclosure);
        if (i2 != 1) {
            throw new Exception("修改申请表节点id和节点名异常");
        }

        //保存消息
            CompletableFuture<Void> f = CompletableFuture.runAsync(() -> {
                if (param.getSendAliyun()) {
                workflowExecService.returnMessagesUtils(param);
                }
            });

    }

    // set WorkflowComplete值
    public WorkflowComplete setWorkflowComplete(ExecProgressDto param) {
        WorkflowComplete workflowComplete = new WorkflowComplete();
        BeanUtils.copyProperties(param, workflowComplete);
        workflowComplete.setDealUser(param.getFullName());
        workflowComplete.setLabel(IdentifyConstant.USER);
        if (param.getFlowCode() == 1 || param.getFlowCode() == 3) {
            workflowComplete.setExamineStatus(2);
        } else {
            workflowComplete.setExamineStatus(1);
        }
        return workflowComplete;
    }

    /**
     * 添加历史任务
     * @author 苏小林
     * @date 2021/1/14 10:49
     * @param: workflowComplete
     * @return: java.lang.String
     */
    public String createHiFlowExce(WorkflowComplete workflowComplete) throws Exception {
        // 添加删除
        workflowComplete.setId(IdGen.generateUUID());
        workflowComplete.setDealUserId(UserUtils.getLoginAppUser().getUserId());
        int i = workflowCompleteMapper.insert(workflowComplete);
        if (i != 1) {
            throw new Exception("添加删除异常");
        }
        return workflowComplete.getId();
    }


    // 流程节点列表
    @Override
    public List<Map<String, Object>> getWorkFlowNodeList(String disclosureId) {
        // 判断是否闭案了
        Disclosure disclosure = disclosureMapper.selectById(disclosureId);
        if ("8C337C68A0FF4F48B0B80C88B895868D".equals(disclosure.getNodeId())) {
          // 查找历史节点记录
            List<Map<String, Object>> nodeRecord = workflowCompleteMapper.getNodeRecord(disclosureId);
            Map<String, Object> map=new HashMap<>();
            map.put("nodeName","闭案");
            map.put("nodeNum",0);
//            map.put("currentNum",0);
            nodeRecord.add(map);
            return nodeRecord;
        }
        return workflowLinkMapper.getWorkFlowNodeList();
    }

    // 消息发送
    @Override
    public void returnMessagesUtils(ExecProgressDto param) {
        try {
            String disclosureId = param.getDisclosureId();
            //指派人
            List<Long> users = new ArrayList<>(param.getUsers());
            if (users != null && users.size() >0) {
                String recipient = null;
                String label = param.getLabel();
                if (IdentifyConstant.ROLE.equals(label)) {
                    //根据角色获取对应的用户id
                    List<String> userInfoByRoleId = userMapper.getUserInfoByRoleId(users);
                    userInfoByRoleId.removeIf(a -> "290".equals(a));
                    recipient = String.join(",", userInfoByRoleId);
                } else {
                    users.removeIf(b -> new Long(290).equals(b));
                    recipient = org.apache.commons.lang.StringUtils.join(users.toArray(), ",");
                }

                if (StringUtils.isNotBlank(recipient)) {
                Map<String, Object> messageMap = Maps.newHashMap();
                messageMap.put("projectId", 1);
                messageMap.put("dataId", disclosureId);
                messageMap.put("title", "专利申请");
                messageMap.put("sender", param.getUserId());
                messageMap.put("recipient", recipient);
//            messageMap.put("examineStatus",param.getNodeName());
                messageMap.put("node_name", param.getNodeName());
                messageMap.put("createDate", new Date());
                messageMap.put("createBy", param.getUserId());
                messageMap.put("updateBy", param.getUserId());
                messageMap.put("status", 2);
                messageMap.put("updateDate", new Date());
                messageMap.put("content", " 尊敬的用户，您在OA系统-专利申请-模块中有新的审批任务，请尽快登录处理！");
                applicationContext.publishEvent(new MessageEvent(this, messageMap));
                }
            }

        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//关键
            log.error("消息发送错误", e);
        }

    }

    //审核转入列表
    @Override
    public IPage<TransferModel> findPatentAuditTransferList(Map<String, Object> param) {
        int pageNum = 1;
        int pageSize = 20;
        if (StringUtils.isNotNull(param.get("pageNum"))) {
            pageNum = Integer.parseInt(String.valueOf(param.get("pageNum")));
        }
        if (StringUtils.isNotNull(param.get("pageSize"))) {
            pageSize = Integer.parseInt(String.valueOf(param.get("pageSize")));
        }
        String taskType = String.valueOf(param.get("taskType"));
        String userId = String.valueOf(param.get("userId"));
        IPage<TransferModel> listPage=new Page();
        List<TransferModel> list = new ArrayList<>();
        Page<TaskTransferModel> page=new Page<>(pageNum,pageSize);
        IPage<TaskTransferModel> findPatentTransferList = workflowExecMapper.findPatentTransferList(page,userId, taskType);
        for (TaskTransferModel patentTransferList : findPatentTransferList.getRecords()) {
            String content = patentTransferList.getContent();
            if (StringUtils.isNotNull(content)) {
                TransferModel transferModel = JSONObject.parseObject(content, TransferModel.class);
                transferModel.setTransferId(patentTransferList.getId());
                transferModel.setCreateBy(patentTransferList.getCreateBy());
                list.add(transferModel);
            }
        }
        listPage.setRecords(list);
        listPage.setTotal(findPatentTransferList.getTotal());
        listPage.setPages(findPatentTransferList.getPages());
        return listPage;

    }

    @Override
    public IPage<TransferModel> findPatentAuditTransferOutList(Map<String, Object> param) {
        int pageNum = 1;
        int pageSize = 20;
        if (StringUtils.isNotNull(param.get("pageNum"))) {
            pageNum = Integer.parseInt(String.valueOf(param.get("pageNum")));
        }
        if (StringUtils.isNotNull(param.get("pageSize"))) {
            pageSize = Integer.parseInt(String.valueOf(param.get("pageSize")));
        }
        String taskType = String.valueOf(param.get("taskType"));
        String userId = String.valueOf(param.get("userId"));
        IPage<TransferModel> list = new Page<>();
        Page<TransferModel> page = new Page<>(pageNum,pageSize);
        switch (taskType) {
            // 个人转出列表
            case "0":
                list = workflowExecMapper.findPatentMyTransferOutList(page,userId, taskType);
                break;
            // 审核转出列表
            case "1":
                List<String> roleList = userMapper.getRoleListByUserIdList(
                        Arrays.asList(String.valueOf(String.valueOf(userId)).split(",")));
                list = workflowExecMapper.findPatentAuditTransferOutList(page,userId, roleList, taskType);
                break;
        }

        for (TransferModel transferModel : list.getRecords()) {
            List<Object> listTransferor = Lists.newArrayList();
            if (transferModel.getTransferorDeptId() != null && transferModel.getTransferorUserId() != null) {
                listTransferor.add(transferModel.getTransferorDeptId());
                listTransferor.add(transferModel.getTransferorUserId());
                transferModel.setUserList(listTransferor);
            }

        }

        return list;
    }

    /**
     * IPR查新沟通
     * @author 苏小林
     * @date 2021/1/11 13:39
     * @param: param
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void iprCommunicate(ExecProgressDto param) throws Exception {
        List<PatentFile> patentFileList = param.getPatentFileList();
        for (PatentFile patentFile : patentFileList) {
            patentFile.setDiscId(param.getDisclosureId());// 交底书id
            patentFile.setOwnerAs(String.valueOf(param.getUserId()));
            patentFile.setCheckType(0);
            patentFile.setPatentFileId(IdGen.generateUUID());
            int i1 = patentFileMapper.insert(patentFile);
            if (i1 != 1) {
                throw new Exception("保存文件异常");
            }
        }
        this.execProgress2(param);
    }

    /**
     * 评审会初审
     *
     * @author 苏小林
     * @date 2021/1/12 10:40
     * @param: param
     */
    @Override
    public void firstTrialPass(ExecProgressDto param) throws Exception {
        String nodeId = param.getNodeId();
        String disclosureId = param.getDisclosureId();
        // 当前节点所有的任务
        List<WorkflowIdentitylink> list = workflowIdentityLinkMapper.findByNodeIdAndDisclosureId(disclosureId, nodeId);
        // ipr的任务列表
        List<WorkflowIdentitylink> iprTaskList = Lists.newArrayList();
        // 评审会成员
        List<Long> judgesUserId = judgesUserMapper.getJudgesUserId(param.getDisclosureId());
        // 建议IPR
        List<Long> adviceIpr = tbPamInventorProposalIprMapper.getAdviceIpr(disclosureId);
        List<Long> intersection = adviceIpr.stream().filter(item -> judgesUserId.contains(item)).collect(toList());
        if (intersection==null || intersection.size() ==0){ // 评审会中不包含建议ipr,需要把建议IPR的审核任务拿出来
            if (adviceIpr.contains(UserUtils.getLoginAppUser().getUserId())) {
                log.error("您不在评审会中，不能参与审核");
                throw new Exception("您不在评审会中，不能参与审核");
            }
            Iterator<WorkflowIdentitylink> iterator = list.iterator();
            for (Long aLong : adviceIpr) {
                while (iterator.hasNext()) {
                    WorkflowIdentitylink next = iterator.next();
                    if (next.getIdentitylinkUserId().equals(aLong)) {
                        iprTaskList.add(next);
                        iterator.remove();
                    }
                }
            }
        }
        // 过滤离职人员
        Iterator<WorkflowIdentitylink> iterator = list.iterator();
        while (iterator.hasNext()) {
            WorkflowIdentitylink next = iterator.next();
            if (next.getStatus() != 0) {
                iprTaskList.add(next);
                iterator.remove();
            }
        }

        if (list.size() == 1) { // 如果除了ipr自己的任务 余下1条任务
            if (iprTaskList.size() != 0) { // 包含IPR自己的任务 和 不在职人员
                for (WorkflowIdentitylink workflowIdentitylink : iprTaskList) {
                    workflowIdentityLinkMapper.deleteByProcessTaskId(workflowIdentitylink.getId());
                    workflowCompleteMapper.delExecProgressById(workflowIdentitylink.getId());
                }
            }

            // 查询交底书相关评审会负责人
            List<Long> list_f = disclosureMapper.getPatentUserIdByDisclosureId(param.getDisclosureId());
            if (list_f == null || list_f.size() == 0) {
                throw new Exception("评审会负责人为空,请联系管理员完善评审会负责人!");
            }
            param.setUsers(list_f);
            param.setLabel(IdentifyConstant.USER);
            param.setJumpForm(JumpConstant.FIRST_TRIAL_FZR_AUDIT);
            if ("7524DFC3666B40C5A6E6EEFD063F06EA".equals(param.getNodeId())) {// 终审
                param.setJumpForm(JumpConstant.FINAL_TRIAL_FZR_AUDIT);
            }
            this.execProgress2(param);
        }

        if (list.size() > 1) { // 如果任务不止1条 删除当前任务并修改历史任务
            this.execProgress3(param);
        }

    }

    /**
     * IPR编写
     * @author 苏小林
     * @date 2021/1/12 15:30
     * @param: param
     */
    @Override
    public void iprEditFile(ExecProgressDto param) throws Exception {
        List<PatentFile> patentFileList = param.getPatentFileList();
        for (PatentFile patentFile : patentFileList) {
            patentFile.setDiscId(param.getDisclosureId());// 交底书id
            patentFile.setOwnerAs(String.valueOf(param.getUserId()));
            patentFile.setCheckType(1);
            patentFile.setPatentFileId(IdGen.generateUUID());
            int i1 = patentFileMapper.insert(patentFile);
            if (i1 != 1) {
                throw new Exception("保存文件异常");
            }
        }
        this.execProgress2(param);
    }

    /**
     * IPR编写完整申请文件
     * @author 苏小林
     * @date 2021/1/13 10:22
     * @param: param
     */
    @Override
    public void iprEditCompleteFile(ExecProgressDto param) throws Exception {
        List<PatentFile> patentFileList = param.getPatentFileList();
        if (patentFileList == null || patentFileList.size() ==0) {
            throw new Exception("完整申请文件不能为空");
        }
        for (PatentFile patentFile : patentFileList) {
            patentFile.setDiscId(param.getDisclosureId());// 交底书id
            patentFile.setOwnerAs(String.valueOf(param.getUserId()));
            patentFile.setCheckType(2);
            patentFile.setPatentFileId(IdGen.generateUUID());
            int i1 = patentFileMapper.insert(patentFile);
            if (i1 != 1) {
                throw new Exception("保存文件异常");
            }
        }

        this.execProgress2(param);
    }

    @Override
    public void creatorReplyIpr(ExecProgressDto param) throws Exception {
        List<PatentFile> patentFileList = param.getPatentFileList();
        for (PatentFile patentFile : patentFileList) {
            if (StringUtils.isBlank(patentFile.getPatentFileId())) {
                patentFile.setDiscId(param.getDisclosureId());// 交底书id
                patentFile.setOwnerAs(String.valueOf(param.getUserId()));
                patentFile.setCheckType(2);
                patentFile.setPatentFileId(IdGen.generateUUID());
                int i1 = patentFileMapper.insert(patentFile);
                if (i1 != 1) {
                    throw new Exception("保存文件异常");
                }
            } else {
                PatentFile patentFile1 = new PatentFile();
                patentFile1.setPatentFileId(patentFile.getPatentFileId());
                patentFile1.setUploadTime(new Date());
                patentFileMapper.updateById(patentFile1);
            }
        }

        this.execProgress2(param);
    }

    //  数据修改
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateDBdata() throws Exception {

        try {
       // 修改指派人
            // 技术负责人查重建议
        workflowIdentityLinkMapper.updateJSFZRCCIdentity();
       // 技术负责人查重建议ipr是无或多个+多ipr查新有多个IPr指派人改成丁红敏
         workflowIdentityLinkMapper.updateCZDIPRIdentity();
         // 多ipr有多个IPr编写权力要求文件改成丁红敏
        workflowIdentityLinkMapper.updateBXQLWJIdentity();

        // 技术负责人选择  变成 评审会终审 审批人改成评审会成员
        // 技术负责人选择待审核数据
        List<WorkflowIdentitylinkModel> list = workflowIdentityLinkMapper.getList();
        // 获取交底书对应评审会成员
        for (WorkflowIdentitylinkModel workflowIdentitylink1:list) {
            QueryWrapper<JudgesUser> queryWrapper1=new QueryWrapper();
            queryWrapper1.eq("del_flag",0);
            queryWrapper1.eq("judges_id",workflowIdentitylink1.getJudgesId());
            List<JudgesUser> judgesUsers = judgesUserMapper.selectList(queryWrapper1);
            // 删除对应待审核数据
            workflowIdentityLinkMapper.deleteByDisclosureId(workflowIdentitylink1.getDisclosureId());
            // 添加对应待审核数据
            for (JudgesUser user:judgesUsers) {
                WorkflowIdentitylink workflowIdentityLink=new WorkflowIdentitylink();
                BeanUtils.copyProperties(workflowIdentitylink1,workflowIdentityLink);
                workflowIdentityLink.setId(IdGen.generateUUID());
                workflowIdentityLink.setIdentitylinkUserId(user.getUserId());
                workflowIdentityLinkMapper.insert(workflowIdentityLink);
            }
        }

        // 评审会终审审批人改成刁总
        workflowIdentityLinkMapper.updatePSHZSIdentity();
        // 删除多个IPR编写申请文件后提交至发明人，发明人主管
        workflowIdentityLinkMapper.deleteIPRBXTJFMRZG();
        //修改节点
        // 评审会终审改成刁总确认
        workflowIdentityLinkMapper.updatePSHZSNodeId();
        // 互审通过后改成刁总确认+修改审批人刁总
        workflowIdentityLinkMapper.updateHSTGDZNodeId();
        // 技术负责人查重+多单ipr查新 变成 ipr查新
        workflowIdentityLinkMapper.updateJSFZRDIPRNodeId();
        // 多ipr编写权力文件 改成编写权力文件
        workflowIdentityLinkMapper.updateDIPRBXQLWJNodeId();
        // 技术负责人选择+评审会初审 变成 评审会终审
        workflowIdentityLinkMapper.updateJSFZRXZCSNodeId();
        // 修改对应的表字段
        workflowIdentityLinkMapper.alertIdentitylinkId();
        //update_time-create_time
        workflowIdentityLinkMapper.alertIdentitylinkDateTime();
        // identitylink_for_node-node_id
        workflowIdentityLinkMapper.alertIdentitylinkNodeId();
        //identitylink_for_disclosure disclosure_id
        workflowIdentityLinkMapper.alertIdentitylinkDisclosureId();
        //status_id-node_name
        workflowIdentityLinkMapper.alertIdentitylinkNodeName();
        //dept_id-identitylink_dept_id
        workflowIdentityLinkMapper.alertIdentitylinkDeptId();
        //group_id-identitylink_group_id
        workflowIdentityLinkMapper.alertIdentitylinkGroupId();
        //identitylink_user-identitylink_user_id
        workflowIdentityLinkMapper.alertIdentitylinkUserId();
            //         修改交底书改的字段
            // 删除flow_parent_id
        workflowIdentityLinkMapper.dorpDisclosureParentId();
            // 修改disc_status_id为node_name
        workflowIdentityLinkMapper.changeDisclosureStatusId();
            // 新增node_id字段
        workflowIdentityLinkMapper.addDisclosureNodeId();
        }catch (Exception e){
            e.printStackTrace();
                throw new Exception(e);

        }


        }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateDBdata1() {
        // 删除多余的指派 当节点为ipr查新+当节点为编写权力要求文件+评审会终审刁总确认
        int i = workflowIdentityLinkMapper.seleteCount();
        for (int j = 0; j < i; j++) {
            workflowIdentityLinkMapper.deleteDYIdentitylink();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateDBdata2() throws Exception {

        try {
        // 修改建议ipr
        // 当节点在ipr查新时+权力要求书+说明书
        workflowIdentityLinkMapper.updateJYIPR();
        //  当节点在评审会初审+当节点在评审会终审时+互审+刁总确认
        workflowIdentityLinkMapper.updateCSZSHSDZ();

        workflowIdentityLinkMapper.alertOpinionDiscId();
        workflowIdentityLinkMapper.addOpinionExecId();
        workflowIdentityLinkMapper.dropStatusId();
        workflowIdentityLinkMapper.addCompleteDisclosureId();
        workflowIdentityLinkMapper.addCompleteExecId();
        workflowIdentityLinkMapper.addCompleteNodeId();
        workflowIdentityLinkMapper.addCompleteUpdateTime();
        workflowIdentityLinkMapper.addCompleteCreateTime();
        workflowIdentityLinkMapper.addCompleteOwnerAs();
        workflowIdentityLinkMapper.addCompleteStatus();
        workflowIdentityLinkMapper.addCompleteDealUser();
        workflowIdentityLinkMapper.addCompleteLabel();
        workflowIdentityLinkMapper.dropCompleteParentId();
        workflowIdentityLinkMapper.updateNodeId();
        workflowIdentityLinkMapper.updateBANodeId();
        workflowIdentityLinkMapper.updateSQTGNodeId();

        // 历史表存处理人
            QueryWrapper<TbGlobalUser> queryWrapper2=new QueryWrapper();
            queryWrapper2.eq("del_flag",0);
            List<TbGlobalUser> list = userMapper.selectList(queryWrapper2);
            for (TbGlobalUser user:list) {
                QueryWrapper queryWrapper1=new QueryWrapper();
                queryWrapper1.eq("deal_user_id",user.getUserId());
                WorkflowComplete workflowComplete1=new WorkflowComplete();
                workflowComplete1.setDealUser(user.getFullName());
                workflowComplete1.setLabel("user");
                workflowCompleteMapper.update(workflowComplete1,queryWrapper1);
            }

            // 待审核所有的数据复制到历史表
        // 获取所有的待审核数据
        QueryWrapper<WorkflowIdentitylink> queryWrapper=new QueryWrapper();
        queryWrapper.eq("del_flag",0);
        List<WorkflowIdentitylink> workflowIdentitylinks = workflowIdentityLinkMapper.selectList(queryWrapper);
        for (WorkflowIdentitylink workflowIdentitylink:workflowIdentitylinks) {
            WorkflowComplete workflowComplete=new WorkflowComplete();
            workflowComplete.setUpdateTime(workflowIdentitylink.getCreateTime());
            BeanUtils.copyProperties(workflowIdentitylink,workflowComplete);
            if (StringUtils.isNotBlank(workflowIdentitylink.getIdentitylinkUserId())) {
                workflowComplete.setDealUserId(workflowIdentitylink.getIdentitylinkUserId());
                workflowComplete.setDealUser(String.valueOf(workflowIdentitylink.getIdentitylinkUserId()));
                workflowComplete.setLabel("user");
            }else  if (StringUtils.isNotBlank(workflowIdentitylink.getIdentitylinkGroupId())){
                workflowComplete.setDealUserId(workflowIdentitylink.getIdentitylinkGroupId());
                workflowComplete.setDealUser(String.valueOf(workflowIdentitylink.getIdentitylinkGroupId()));
                workflowComplete.setLabel("role");
            }
            workflowComplete.setExamineStatus(0);
            workflowCompleteMapper.insert(workflowComplete);

            switch (workflowComplete.getNodeId()){
                case "19181F68A04841F2AE079A8D52925200":
                    workflowIdentitylink.setJumpForm(JumpConstant.DEPT_AUDIT);
                    break;
                case "003BFA10D8934DF992E34DED81787CCC":
                    workflowIdentitylink.setJumpForm(JumpConstant.CREATEBY_RESUBMIT_AUDIT);
                    break;
                case "39DB703EDD0A4A20AF858FBBED6BF6ED":
                    workflowIdentitylink.setJumpForm(JumpConstant.IPR_CX_AUDIT);
                    break;
                case "6E7520D906344079B22229F1FB52E114":
                    workflowIdentitylink.setJumpForm(JumpConstant.CREATEBY_REPLAYIPR_AUDIT);
                    break;
                case "97BF5B1F73414EA9BBDB55C62D46B981":
                    workflowIdentitylink.setJumpForm(JumpConstant.JUDGES_FIRST_TRIAL_AUDIT);
                    break;
                case "8E7520D906358079B25479F1FB52E258":
                    workflowIdentitylink.setJumpForm(JumpConstant.FIRST_TRIAL_FZR_AUDIT);
                    break;
                case "270BFB5523784223B122A3ABC5D40793":
                    workflowIdentitylink.setJumpForm(JumpConstant.FIRST_TRIAL_ZJL_CONFIRM_AUDIT);
                    break;
                case "3AE5CBF5E43E444D8256929EC6BFF2C8":
                    workflowIdentitylink.setJumpForm(JumpConstant.IPR_BX_AUDIT);
                    break;
                case "7524DFC3666B40C5A6E6EEFD063F06EA":
                    workflowIdentitylink.setJumpForm(JumpConstant.JUDGES_FINAL_TRIAL_AUDIT);
                    break;
                case "04198012fc1c49b68959c05bd492d80f":
                    workflowIdentitylink.setJumpForm(JumpConstant.FINAL_TRIAL_FZR_AUDIT);
                    break;
                case "77409ADFDC384F46AA3F6B415893E432":
                    workflowIdentitylink.setJumpForm(JumpConstant.FINAL_TRIAL_ZJL_CONFIRM_AUDIT);
                    break;
                case "67409ADFDC384E46AA3F6B410113E495":
                    workflowIdentitylink.setJumpForm(JumpConstant.IPR_EDIT_COMPLETE_FILE);
                    break;
                case "736ca4d2a36e475daefd92e9828a1489":
                    workflowIdentitylink.setJumpForm(JumpConstant.IPR_HS_AUDIT);
                    break;
                case "D83445C2BFAA4B1CBA275DD1640D3EFE":
                    workflowIdentitylink.setJumpForm(JumpConstant.HS_ZJL_CONFIRM_AUDIT);
                    break;
                case "88A4B87FDF314252902F8FA65B2358BC":
                    workflowIdentitylink.setJumpForm(JumpConstant.PATENT_SUBMIT);
                    break;
                case "88c90b93b2894fe5bd17bb7e3dca6f24":
                    workflowIdentitylink.setJumpForm(JumpConstant.WAIT_FOR_NOTICE);
                    break;
                case "253CBECAAB5342CBA4EFC3FE56B1F34C":
                    workflowIdentitylink.setJumpForm(JumpConstant.APPLICATION_FEE_PAID);
                    break;
            }
            workflowIdentityLinkMapper.updateById(workflowIdentitylink);
        }

        List<Map<String, Object>> maps = workflowIdentityLinkMapper.getFlowHiExecId();
        for (Map<String, Object> map:maps) {
            String flowHiExecId = String.valueOf(map.get("flowHiExecId"));
            String opinionId = String.valueOf(map.get("opinionId"));
            workflowIdentityLinkMapper.updateOpin(flowHiExecId,opinionId);

        }
        }catch (Exception e){
            e.printStackTrace();
            throw new Exception(e);
        }
    }

    // 修改节点为评审会初审终审，评审会初审终审确认的指派人
        public void updateIdentityAndHi(Long patentUserId,List<List<Long>> users, List<RuningTaskModel> runingTask,List<Long> adviceIprs) throws Exception {
            // 修改正在审批人
            for (RuningTaskModel data:runingTask) {
                List<Long> listUser = new ArrayList<>();
                String disclosureId = data.getDisclosureId();
                // 查找审批过评审会成员
                QueryWrapper<WorkflowComplete> wrapper = new QueryWrapper<>();
                wrapper.ne("examine_status",0);
                wrapper.eq("disclosure_id",disclosureId);
                wrapper.eq("node_id",data.getNodeId());
                List<WorkflowComplete> workflowCompletes = workflowCompleteMapper.selectList(wrapper);
                // 添加用户是ipr
                // 获取ipr
                List<Long> adviceIprsDB=null;
                if (adviceIprs == null) {
                    adviceIprsDB = tbPamInventorProposalIprMapper.getAdviceIpr(disclosureId);
                    if (adviceIprsDB.size()==0){
                        throw new Exception("建议IPR为空");
                    }
                }else{
                    adviceIprsDB=adviceIprs;
                }
                Long aLong = adviceIprsDB.get(adviceIprsDB.size() - 1);
                listUser.add(aLong);
                if (users != null && !users.isEmpty()) {
                    for (List<Long> user : users) {
                        if (!StringUtils.toLong(user.get(1)).equals(aLong)) {
                            listUser.add(StringUtils.toLong(user.get(1)));
                        }
                    }
                }

                // 获取修改后的评审会成员已审核过的成员
                List<Long> collect = workflowCompletes.stream().filter(userId -> listUser.contains(userId.getDealUserId()))
                        .collect(Collectors.toList()).stream().map(WorkflowComplete::getDealUserId).collect(Collectors.toList());

                // 删除与之交底书对应待审核的数据
                int i1 = workflowIdentitylinkMapper.deleteByDisclosureId(disclosureId);
                if (i1 == 0) {
                    throw new Exception("删除与之交底书对应待审核的数据返回值为0");
                }
                // 删除与之交底书对应历史表待审核的数据 排除修改后的评审会成员仍有的旧成员
                int i = workflowCompleteMapper.deleteHiForDisclosureAndNodeIdAndDealUserId(disclosureId, data.getNodeId(),collect);
                if (i == 0) {
                    throw new Exception("删除与之交底书对应历史表待审核的数据返回值为0");
                }

                if ("8E7520D906358079B25479F1FB52E258".equals(data.getNodeId()) || "04198012fc1c49b68959c05bd492d80f".equals(data.getNodeId())) {
                    this.insertIdentityAndHi(data, patentUserId);
                } else {
                    if (listUser != null && !listUser.isEmpty()) {
                        for (Long user : listUser) {
                            if(!collect.contains(user))
                                this.insertIdentityAndHi(data, user);
                        }
                    }
                }
            }
        }

    // 添加正在执行和历史数据
        public void insertIdentityAndHi(RuningTaskModel data,Long identitylinkUserId) throws Exception {
            WorkflowIdentitylink workflowIdentitylink=new WorkflowIdentitylink();
            BeanUtils.copyProperties(data,workflowIdentitylink);
            workflowIdentitylink.setId(IdGen.generateUUID());
            workflowIdentitylink.setIdentitylinkUserId(identitylinkUserId);
            int insert = workflowIdentitylinkMapper.insert(workflowIdentitylink);
            if (insert == 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//关键
                throw new Exception("保存待审核数据返回值为0");
            }
            // 保存历史表
            WorkflowComplete workflowComplete=new WorkflowComplete();
            BeanUtils.copyProperties(workflowIdentitylink,workflowComplete);
            workflowComplete.setUpdateTime(workflowIdentitylink.getCreateTime());
            workflowComplete.setLabel("user");
            workflowComplete.setDealUserId(workflowIdentitylink.getIdentitylinkUserId());
            workflowComplete.setDealUser(String.valueOf(workflowIdentitylink.getIdentitylinkUserId()));
            int insert1 = workflowCompleteMapper.insert(workflowComplete);
            if (insert1 == 0) {
                throw new Exception("保存待审核历史表数据返回值为0");
            }
        }

    @Override
    public Integer getCurrentNodeNum(String disclosureId) {
        Integer currentNodeNum = null;
                currentNodeNum = workflowIdentitylinkMapper.getCurrentNodeNum(disclosureId);
        if (currentNodeNum == null){
            // 查找历史表
            currentNodeNum = workflowCompleteMapper.getCurrentNodeNum(disclosureId);

            if (currentNodeNum == null) {
                // 判断是否闭案了
                Disclosure disclosure = disclosureMapper.selectById(disclosureId);
                if ("8C337C68A0FF4F48B0B80C88B895868D".equals(disclosure.getNodeId())) {
                    // 查找历史节点记录
                    List<Map<String, Object>> nodeRecord = workflowCompleteMapper.getNodeRecord(disclosureId);
                    currentNodeNum = nodeRecord.size()+1;
                }
            }
        }
        return currentNodeNum;
    }

//    ipr修改案卷号
    @Override
    public void updateArchivesNum(Map<String, Object> param) throws Exception {
        // 修改交底书名称
        Disclosure disclosure = StringUtils.toJavaBean(param, Disclosure.class);
        int i = disclosureMapper.updateById(disclosure);
        if (i != 1) {
            throw new Exception("修改案卷号信息失败");
        }
    }

//    IPR互审
    @Override
    public void iprMutualAudit(ExecProgressDto param) throws Exception {
        String nodeId = param.getNodeId();
        String disclosureId = param.getDisclosureId();
        // 当前节点所有的任务
        List<WorkflowIdentitylink> list = workflowIdentityLinkMapper.findByNodeIdAndDisclosureId(disclosureId, nodeId);
        // ipr的任务列表
        List<WorkflowIdentitylink> iprTaskList = Lists.newArrayList();
        // 过滤离职人员
        Iterator<WorkflowIdentitylink> iterator = list.iterator();
        while (iterator.hasNext()) {
            WorkflowIdentitylink next = iterator.next();
            if (next.getStatus() != 0) {
                iprTaskList.add(next);
                iterator.remove();
            }
        }

        if (list.size() == 1) { // 如果除了ipr自己的任务 余下1条任务
            if (iprTaskList.size() != 0) { // 包含IPR自己的任务 和 不在职人员
                for (WorkflowIdentitylink workflowIdentitylink : iprTaskList) {
                    workflowIdentityLinkMapper.deleteByProcessTaskId(workflowIdentitylink.getId());
                    workflowCompleteMapper.delExecProgressById(workflowIdentitylink.getId());
                }
            }
            this.execProgress2(param);
        }

        if (list.size() > 1) { // 如果任务不止1条 删除当前任务并修改历史任务
            this.execProgress3(param);
        }


    }

    @Override
    public void iprReMutualAudit(ExecProgressDto param,Integer type) throws Exception {
        // 删除反馈意见通过交底书id
        tbPamJudgesReviewRecordMapper.deleteByDisclosureId(param.getDisclosureId(),type);
        // 执行流程
        this.execProgress2(param);
    }

    @Override
    public void firstTrialRe(ExecProgressDto param) throws Exception {
        // 删除反馈意见通过交底书id
        // 执行流程
        this.execProgress2(param);
    }


    /**
     * @Description: 专利统计-国内在审
     * @Param:  date 日期
     * @Author: liuqinghua
     * @Date: 2021/9/6
     */
    public Integer getPatentStatistics(String date,boolean isNow) {
        return workflowExecMapper.getPatentStatistics(date,isNow);
    }
}

